package com.dc.seckill.service;

import com.dc.seckill.dao.OrderDao;
import com.dc.seckill.domain.MiaoshaOrder;
import com.dc.seckill.domain.MiaoshaUser;
import com.dc.seckill.domain.OrderInfo;
import com.dc.seckill.exception.GlobalException;
import com.dc.seckill.result.CodeMsg;
import com.dc.seckill.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @模块 订单模块
 * @作者 djs
 * @时间 2018/3/21 22:44
 * @版本 V1.0
 * @描述 提供对订单信息进行处理的一些方法
 */
@Service
public class OrderService {

    private Logger log = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    OrderDao orderDao;

    public MiaoshaOrder queryOrderByUserIdGoodsId(Long userId, Long goodsId) {
        log.info("根据用户ID【"+userId+"】商品ID【"+goodsId+"】查询秒杀订单");
        //1:参数校验
        if(StringUtils.isEmpty(userId) || StringUtils.isEmpty(goodsId)){
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("用户ID和商品ID不能为空"));
        }

        //2:获取秒杀订单信息
        return orderDao.queryOrderByUserIdGoodsId(userId,goodsId);
    }

    /**
     * 生成订单
     * @params [user, goods]
     * @returns com.dc.seckill.domain.OrderInfo
     */
    @Transactional
    public OrderInfo createOrder(MiaoshaUser user, GoodsVo goods) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsPrice(goods.getMiaoshaPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        orderDao.insert(orderInfo);
        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setGoodsId(goods.getId());
        miaoshaOrder.setOrderId(orderInfo.getId());
        miaoshaOrder.setUserId(user.getId());
        orderDao.insertMiaoshaOrder(miaoshaOrder);
        return orderInfo;
    }
}
